<?php

namespace app\admin\service\user_profile\userArchive\selfTesting;

use app\admin\service\user_profile\userArchive\evaluationArchive\EvaluationArchiveService;
use app\common\Message;
use app\model\archives_model\UserArchiveModel;
use app\model\archives_model\UserArchiveTypeModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOnlineModel;
use PhpOffice\PhpWord\TemplateProcessor;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Service;

class SelfTestingService extends Service
{
    use Message;

    /**
     * @param $data
     * @return true
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function getOverview($data): bool
    {
        //用户基本信息
        $getUserInfo = new EvaluationArchiveService($this->app);
        $info = $getUserInfo->getUserInfo($data);
        //个人自评档案统计
        if (check_array_key('isAbandon', $data)) {
            //废弃档案数据
            $wheres = [
                ['user_id', '=', $data['user_id']],
                ['is_repeal', '=', 1],
                ['type_id', '=', 1],
            ];
        } else {
            //正常档案数据
            $wheres = [
                ['user_id', '=', $data['user_id']],
                ['is_repeal', '=', 0],
                ['type_id', '=', 1],
            ];
        }
        $field = ['id,user_id,time,source'];
        $recode = UserArchiveModel::query()->where($wheres)->field($field)->select();
        $totalCount = count($recode);
        if ($totalCount > 0) {
            $ret = [
                'max_time' => 0,//最新一次的时间
                'min_time' => 0,//档案首次建立时间
                'to_date' => 0,//距今天数
                'total' => $totalCount,//总数
                'total_proportion' => 100,
                'self' => 0,
                'self_proportion' => 0,
                'online' => 0,
                'online_proportion' => 0,
                'offline' => 0,
                'offline_proportion' => 0,
                'team' => 0,
                'team_proportion' => 0,
            ];
            if ($ret['total'] > 0) {
                $timeArray = array_column($recode->toArray(), 'time');
                $ret['min_time'] = min($timeArray);
                $ret['max_time'] = max($timeArray);
                $ret['to_date'] = ceil((time() - $ret['min_time']) / (24 * 60 * 60));
                // 初始化来源统计数组
                $sourceCount = array_fill_keys([1, 2, 5, 6, 7], 0);
                // 统计每种来源的数量
                foreach ($recode as $item) {
                    if (isset($sourceCount[$item['source']])) {
                        $sourceCount[$item['source']]++;
                    }
                }
                // 映射渠道到返回结果结构
                $channelMapping = [
                    1 => 'self',
                    2 => 'online',
                    3 => 'offline',
                    4 => 'team',
                ];
                // 更新返回结果
                foreach ($sourceCount as $channel => $count) {
                    if (isset($channelMapping[$channel])) {
                        $ret[$channelMapping[$channel]] = $count;
                        $proportionKey = $channelMapping[$channel] . '_proportion';
                        $ret[$proportionKey] = $totalCount > 0 ? removeTrailingZero(number_format($count / $totalCount * 100, 1)) : 0;
                    }
                }
            }
            $info['archives'] = $ret;
        } else {
            $info = [];
        }
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @param $data
     * @return bool
     * @throws DbException
     */
    public function getRecode($data): bool
    {
        if (check_array_key('isAbandon', $data)) {
            //废弃档案数据
            $where = [
                ['user_id', '=', $data['user_id']],
                ['type_id', '=', 1],
                ['is_repeal', '=', 1],
            ];
        } else {
            //正常档案数据
            $where = [
                ['user_id', '=', $data['user_id']],
                ['type_id', '=', 1],
                ['is_repeal', '=', 0],
            ];
        }
        $return = UserArchiveModel::query()->where($where)->with(['getUserInfo'])->field('id,update_uid,type_id,time,source,source_id')
            ->order('time desc')->paginate($data['pageSize']);
        $ret = $return->toArray();
        # 计算当前页的起始索引
        $start_index = ($ret['current_page'] - 1) * $ret['per_page'];
        // 更新数据并添加 num 字段
        $ConsultOfflineModel = new ConsultOfflineModel();
        $ConsultOnlineModel = new ConsultOnlineModel();
        foreach ($return as $index => &$item) {
            $item['num'] = ($start_index + $index === $ret['total'] - 1) ? 1 : ($ret['total'] - ($start_index + $index));
            switch ($item['source']) {
                case 1:
                    $item['source'] = '个人信息设置';
                    $item['describe'] = '用户自行更新个人自评表。';
                    break;
                case 2:
                    $item['source'] = '线下预约';
                    $item['describe'] = '线下预约时,由咨询师发布个人自评表,用户填写后更新。';
                    $info = $ConsultOfflineModel->with(['consult'])->find($item['source_id']);
                    $item['consult_name'] = $info['consult_name']??'';
                    break;
                case 3:
                    $item['source'] = '线上咨询';
                    $item['describe'] = '线上咨询时,由咨询师发布个人自评表,用户填写后更新。';
                    $info = $ConsultOnlineModel->with(['consult'])->find($item['source_id']);
                    $item['consult_name'] = $info['consult_name']??'';
                    break;
                case 4:
                    $item['source'] = '团体活动自评';
                    $item['describe'] = '团体活动时,由管理员发布个人自评表,用户填写后更新。';
                    break;
                default:
                    $item['source'] = '未知来源';
                    $item['describe'] = '无可用描述。';
            }
        }
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    public function exportRecode($data)
    {
        // 导出个人自评
        $self_evaluation_info = $this->selfEvaluationInfo($data);
        if (!empty($self_evaluation_info)) {
            //开始导出
            $ret = $this->exportSelfEvaluationRecord($this->result);
        } else {
            $this->result = 0;
            $this->message = '暂无数据！';
            return false;
        }
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * 获取个人自评信息
     * @param $data
     */
    public function selfEvaluationInfo($data)
    {
        try {
            $param = $data;
            $key = ['user_id', 'type_id'];
            foreach ($key as $item) {
                if (!check_array_key($item, $param)) {
                    return error('缺少参数!');
                }
            }
            if (!isset($param['pageSize'])) {
                $param['page'] = 1;
                $param['pageSize'] = 1;
            }
            $where = [
                ['user_id', '=', $param['user_id']],
                ['type_id', '=', $param['type_id']],
            ];
            if (isset($param['result_id'])) {
                //只有线下。线上查结果需要
                $return = UserArchiveModel::query()->where('id', $param['result_id'])->find();
            } else {
                if (!isset($param['type'])) {
                    //用户列表这边的数据
                    $return = UserArchiveModel::query()->where($where)->with(['getUserInfo'])->order('time desc')->limit(1)->select();
                } else {
                    //档案库的用的数据
                    if (check_array_key('isAbandon', $param)) {
                        //废弃档案
                        $where[] = ['is_repeal', '=', 0];
                    } else {
                        //正常档案
                        $where[] = ['is_repeal', '=', 0];
                    }
                    $return = UserArchiveModel::query()->where($where)->order('time desc')->paginate($param['pageSize']);
                }
            }
            //获取资料
            $whereArr = [];
            $whereArr[] = ['id', '=', 1];
            //通用模板
            $model = UserArchiveTypeModel::query()
                ->where($whereArr)
                ->with(['templates' => function (Query $query) {
                    $query->with(['templateOptions'])->where('is_can_custom', '=', 0)->append(['is_custom']);
                }])
                ->select();
            $list = $model->toArray();
            foreach ($list as $key => $value) {
                $temp = [];
                $templateList = [];
                $templateList = set_array_key($value['templates']);
                array_to_tree($templateList, $temp);
                $temp = array_values($temp);
                $list[$key]['templates'] = $temp;
            }
            $date = $list[0]['templates'][0]['children'];

            // $content = [];
            foreach ($date as $key => $item) {
                // $content[$key]['title'] = $item['name'];
                foreach (json_decode($return[0]['content']) as $value) {
                    $str = json_decode(json_encode($value), true);
                    if ($str['questionId'] != 218) {
                        foreach ($date[$key]['templateOptions'] as $kk => $v) {
                            if ($v['id'] == $str['answersId']) {
                                $date[$key]['is_answer'] = $v['name'];
                                break 2;
                            }
                        }
                    } else {
                        $date[$key]['is_answer'] = $str['answersId'];
                        break;

                    }
                }
            }
            $ret['data'] = $return;
            $ret['question'] = $date;
            $this->result = $ret;
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage() . $e->getLine();
            return false;
        }
    }

    /**
     * 导出个人自评记录
     * @param $data
     * @return string
     */
    public function exportSelfEvaluationRecord($data): string
    {
        $templateProcessor = new TemplateProcessor('./archive_template/SelfEvaluationRecordInfo.docx');
        $templateProcessor->setValue('record_title', '个人自评记录'); // 档案标题
        $templateProcessor->setValue('record_end_time', date('Y年m月d日', $data['data'][0]['time'])); // 档案最后更新时间
        // $remark = '用户共更新个人自评记录：'.$data['total'].'次。每次更新记录如下：';
        // $templateProcessor->setValue('record_remark', $remark);
        /*个人自评记录-开始*/
        $templateProcessor->cloneBlock('result_block', count($data['question']), true, true);
        foreach ($data['question'] as $key => $value) {
            $index = $key + 1;
            // $templateProcessor->setValue('record_time#' . $index, date('Y年m月d日',$value['time']));  //时间
            // $templateProcessor->setValue('record_num#' . $index, '第'.$value['num'].'次');  //第几次
            // $templateProcessor->setValue('record_source#' . $index, $value['source']);  //自评记录来源
            $templateProcessor->setValue('question#' . $index, $value['name']); //负责咨询师
            $templateProcessor->setValue('answer#' . $index, $value['is_answer']); //记录来源说明
            // $templateProcessor->setValue('blank#' . $index, ' '); //空格
        }
        /*个人自评记录-结束*/

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/archive_template_recode/self_evaluation_record_info/' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('.' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs('.' . $save_name . $ext);
        return $save_name . $ext;
    }

}